package com.zaoqi.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.zaoqi.pojo.Result;
import com.zaoqi.utils.JwtUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

@Slf4j
@Component
public class LoginCheckInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object handler) throws Exception {
        // 获取请求url
        String url = req.getRequestURL().toString();
        log.info("请求的url: {}", url);
        // 排除根路径 "/" 的请求
        if (url.equals("http://localhost:8080/")) {
            log.info("访问根路径, 放行...");
            return true;
        }
        // 如果是登录请求，直接放行
        if (url.contains("login") || url.contains("register") || url.contains("reset-pwd")) {
            log.info("登录或注册操作, 放行...");
            return true;
        }
        // 获取请求头中的 Authorization 字段
        String authHeader = req.getHeader("Authorization");
        // 判断 Authorization 请求头是否存在，且格式是否正确
        if (!StringUtils.hasLength(authHeader) || !authHeader.startsWith("Bearer ")) {
            log.info("Authorization 请求头为空或格式不正确, 返回未登录的信息");
            Result error = Result.error("NOT_LOGIN");
            String notLogin = JSONObject.toJSONString(error);
            resp.getWriter().write(notLogin);
            return false;
        }
        String jwt=authHeader.substring(7);
        log.info(jwt);
        // 解析token，如果解析失败，返回错误结果（未登录）
        try {
            JwtUtils.parseJWT(jwt);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("解析令牌失败, 返回未登录错误信息");
            Result error = Result.error("NOT_LOGIN");
            String notLogin = JSONObject.toJSONString(error);
            resp.getWriter().write(notLogin);
            return false;
        }
        // 令牌合法, 放行
        log.info("令牌合法, 放行");
        return true;
    }

    @Override //目标资源方法运行后运行
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
        System.out.println("postHandle ...");
    }
    @Override //视图渲染完毕后运行, 最后运行
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        System.out.println("afterCompletion...");
    }
}
